<template>
  <div class="blog-form-container">
    <div class="blog-form-header">
      <h2>新建博客</h2>
    </div>
    <el-form ref="blogFormRef" :model="blogForm" :rules="blogFormRules" label-width="100px" class="blog-form">
      <el-form-item label="标题" prop="title">
        <el-input v-model="blogForm.title" placeholder="请输入博客标题"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <!-- 修改分类选择器 -->
        <el-select v-model="blogForm.categoryId" placeholder="请选择分类" :disabled="loadingCategories">
          <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <!-- 替换原有的el-input为v-md-editor -->
        <v-md-editor v-model="blogForm.content" 
                    height="400px" 
                    placeholder="请输入Markdown格式的博客内容"
                    @upload-image="handleUploadImage"></v-md-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// 移除本地Markdown编辑器导入和配置
import { useRouter } from 'vue-router'
import { blogApi } from '@/api/blogApi'
import { blogFormRules } from '@/utils/formRules'
import { categoryApi } from '@/api/categoryApi'
import { ElMessage } from 'element-plus'


const router = useRouter()

const blogFormRef = ref(null)
// 修改表单数据结构
const blogForm = ref({
  title: '',
  categoryId: null, // 将category改为categoryId
  category: null,
  content: ''
})

const categories = ref([])
const loadingCategories = ref(false)
const loading = ref(false)

const handleSubmit = async () => {
  if (!blogFormRef.value) return
  if (!blogFormRef.value.validate()) return
  try {
    // Validate form
    await blogFormRef.value.validate()
    // If validation passes, submit form
    loading.value = true
    blogForm.value.category = categories.value.find(category => category.id === blogForm.value.categoryId)
    await blogApi.createBlog(blogForm.value)
    router.push('/blogs')
  } catch (error) {
    console.error('Validation failed:', error)
    return
  }
}

const handleUploadImage = async (file) => {
  try {
    // 上传图片到服务器
    const formData = new FormData()
    formData.append('file', file)
    const response = await uploadApi.uploadImage(formData)
    // 返回图片URL
    return response.data.url
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
    return null
  }
}

const cancel = () => {
  router.push('/blogs')
}
onMounted(async () => {
  loadingCategories.value = true
  try {
    const response = await categoryApi.getAllCategories()
    categories.value = response.data
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loadingCategories.value = false
  }
})

// 添加组件卸载时的清理逻辑
onUnmounted(() => {
  // 清空表单数据
  blogForm.value = { title: '', category: null, content: '' }
  // 重置编辑器实例
  if (blogFormRef.value) {
    blogFormRef.value.resetFields()
  }
})
</script>


<style scoped>
.blog-form-container {
  max-width: 800px;
  margin: 0 auto;
}

.blog-form-header {
  margin-bottom: 20px;
}

.blog-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}
</style>